package com.xhs.interceptor;

import com.xhs.constant.Constants;
import com.xhs.utils.TraceIdUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @desc: 日志拦截器，对日志增加唯一标识
 * @projectName: mybatis-flex-demo
 * @author: xhs
 * @date: 2025-01-16 周四 16:33
 * @version: JDK 1.8
 */
@Component
public class LoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 优先从请求头获取traceId，不存在则生成新的
        String traceId = request.getHeader(Constants.TRACE_ID);
        if (!StringUtils.hasLength(traceId)) {
            // 生成TraceId
            traceId = TraceIdUtil.generateTraceId();
        }
        // 设置TraceId
        TraceIdUtil.setTraceId(traceId);
        // 设置TraceId到响应头
        response.setHeader(Constants.TRACE_ID, traceId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清除TraceId
        TraceIdUtil.removeTraceId();
    }
}
